package psmanager.swing;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Date;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

import psmanager.db.DBManager;
import psmanager.db.types.Adresa;
import psmanager.db.types.Cuvar;
import psmanager.db.types.Doktor;
import psmanager.db.types.Mjesto;
import psmanager.db.types.Osoba;
import psmanager.db.types.Zatvorenik;
import psmanager.swing.model.OsobaModel;

import com.toedter.calendar.JDateChooser;

public class CoolDialog extends JDialog {
	private static final long serialVersionUID = 1111769959533248142L;
	
	public static final int TYPE_ADD = 0;
	public static final int TYPE_VIEW = 1;
	public static final int TYPE_EDIT = 2;

	private final JFrame owner;

	private Adresa addressToSave;

	private JButton addressButton;
	
	private AddressDialog addressDialog;

	private final DBManager dbm;

	private final JTable osobaTable;

	private final int dialogtype;
	
	private Osoba uredenik;
	
	public CoolDialog(final JFrame owner, final DBManager dbm,
			final JTable osobaTable, int dialogtype) {
		super(owner);
		this.owner = owner;
		this.dbm = dbm;
		this.dialogtype = dialogtype;
		this.osobaTable = osobaTable;
		owner.setEnabled(false);

		
		
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				owner.setEnabled(true);
			}
		});
		
		uredenik = null;
		
		initGUI(dialogtype);
	}

	@SuppressWarnings("serial")
	private void initGUI(int dialogtype) {

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation(screenSize.width / 2 - 200, screenSize.height / 2 - 200);
		setSize(400, 400);

		setLayout(new BorderLayout());

		JPanel mainPanel = new JPanel();
		mainPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
		add(new JScrollPane(mainPanel));

		final JComboBox tip = new JComboBox(new String[] { "Čuvar", "Doktor",
				"Zatvorenik" });
		final JTextField jmbg = new JTextField();
		final JTextField ime = new JTextField();
		final JTextField prezime = new JTextField();
		addressButton = new JButton("Dodaj");
		final CoolDialog dialogRef = this;
		addressButton.setAction(new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(addressDialog == null)
					addressDialog = new AddressDialog(dialogRef);
				addressDialog.setVisible(true);
			}
		});
		final JDateChooser datumRod = new JDateChooser();
		final JButton dodajDosje = new JButton("Nije implementirano!");

		
		if (dialogtype == TYPE_EDIT || dialogtype == TYPE_VIEW)
		{
						
			// Postavi vrijednosti polja
			OsobaModel model = (OsobaModel) osobaTable.getModel();
			uredenik = model.getOsoba(osobaTable.getSelectedRow());
			
			ime.setText(uredenik.getIme());
			prezime.setText(uredenik.getPrezime());
			jmbg.setText(uredenik.getJmbg());
			datumRod.setDate(uredenik.getRodjen());
			if (uredenik instanceof Doktor)
				tip.setSelectedIndex(1);
			if (uredenik instanceof Cuvar)
				tip.setSelectedIndex(0);
			if (uredenik instanceof Zatvorenik)
				tip.setSelectedIndex(2);
					
			addressButton.setText(uredenik.getPrebivaliste().getUlica() + " " + uredenik.getPrebivaliste().getKucniBroj());
			
			// Postavi address dialog
			addressDialog = new AddressDialog(this);
			this.setEnabled(true);
			
			// Postavi adresu
			addressToSave = uredenik.getPrebivaliste();
			
		}
		
		if (dialogtype == TYPE_VIEW)
		{
			jmbg.setEditable(false);
			ime.setEditable(false);
			prezime.setEditable(false);
			datumRod.setEnabled(false);
			tip.setEditable(false);
			tip.setEnabled(false);
		}
		
		JPanel gridPanel = new JPanel(new GridLayout(8, 2, 8, 8));
		mainPanel.add(gridPanel, BorderLayout.CENTER);

		gridPanel.add(new JLabel("Osoba: "));
		tip.setPreferredSize(new Dimension(150, 20));
		gridPanel.add(tip);

		gridPanel.add(new JLabel("JMBG: "));
		gridPanel.add(jmbg);

		gridPanel.add(new JLabel("Ime: "));
		gridPanel.add(ime);

		gridPanel.add(new JLabel("Prezime: "));
		gridPanel.add(prezime);

		gridPanel.add(new JLabel("Adresa: "));
		gridPanel.add(addressButton);

		gridPanel.add(new JLabel("Datum rođenja: "));
		gridPanel.add(datumRod);

		gridPanel.add(new JLabel("Dodaj dosje: "));
		gridPanel.add(dodajDosje);

		final CoolDialog tmp = this;

		Action editAction = new AbstractAction("Uredi") {
			@SuppressWarnings("unchecked")
			public void actionPerformed(ActionEvent event) {

				if (jmbg.getText().equals(""))
					JOptionPane.showMessageDialog(tmp,
							"JMBG nije dobro unešen!", "Pogreška kod unosa!",
							JOptionPane.ERROR_MESSAGE);
				else if (ime.getText().equals(""))
					JOptionPane.showMessageDialog(tmp,
							"Ime nije dobro unešeno!", "Pogreška kod unosa!",
							JOptionPane.ERROR_MESSAGE);
				else if (prezime.getText().equals(""))
					JOptionPane.showMessageDialog(tmp,
							"Prezime nije dobro unešeno!",
							"Pogreška kod unosa!", JOptionPane.ERROR_MESSAGE);
				else {

					uredenik.setIme(ime.getText());
					uredenik.setPrezime(prezime.getText());
					uredenik.setJmbg(jmbg.getText());
					uredenik.setPrebivaliste(addressToSave);
					uredenik.setRodjen(datumRod.getDate());
					
					// Provjeri je li bilo promjene zanimanja
					if (provjeriZanimanje(uredenik, tip))
						// Ako nije, store
						dbm.store(uredenik);

					else
					{
						Osoba novaOsoba = napraviNovuOsobu(tip.getSelectedIndex(), uredenik);
						dbm.deleteOsoba(uredenik.getJmbg());
						
						dbm.store(novaOsoba);
						
					}
										
					osobaTable.setModel(new OsobaModel((List<Osoba>) dbm
							.grabAllByClass(Osoba.class), dbm));

					tmp.setVisible(false);
					owner.setEnabled(true);

				}

			}
		};
		
		Action addAction = new AbstractAction("Dodaj") {
			@SuppressWarnings("unchecked")
			public void actionPerformed(ActionEvent event) {

				if (jmbg.getText().equals(""))
					JOptionPane.showMessageDialog(tmp,
							"JMBG nije dobro unešen!", "Pogreška kod unosa!",
							JOptionPane.ERROR_MESSAGE);
				else if (ime.getText().equals(""))
					JOptionPane.showMessageDialog(tmp,
							"Ime nije dobro unešeno!", "Pogreška kod unosa!",
							JOptionPane.ERROR_MESSAGE);
				else if (prezime.getText().equals(""))
					JOptionPane.showMessageDialog(tmp,
							"Prezime nije dobro unešeno!",
							"Pogreška kod unosa!", JOptionPane.ERROR_MESSAGE);
				else {

					Osoba osoba;

					if (tip.getSelectedItem().toString().equals("Čuvar")) {
						osoba = new Cuvar(ime.getText(), prezime.getText(),
								jmbg.getText(), addressToSave, datumRod
										.getDate(), null, null, null, 0.0, 0,
								new Date(), null);
					} else if (tip.getSelectedItem().toString()
							.equals("Doktor")) {
						osoba = new Doktor(ime.getText(), prezime.getText(),
								jmbg.getText(), addressToSave, datumRod
										.getDate(), null, null, null);
					} else {
						osoba = new Zatvorenik(ime.getText(),
								prezime.getText(), jmbg.getText(),
								addressToSave, datumRod.getDate(), null, null,
								null, -1, new Date(), null, null);
					}

					dbm.store(osoba);

					osobaTable.setModel(new OsobaModel((List<Osoba>) dbm
							.grabAllByClass(Osoba.class), dbm));

					tmp.setVisible(false);
					owner.setEnabled(true);

				}

			}
		};
		addAction.putValue(Action.SHORT_DESCRIPTION, "Dodaj novu osobu.");
		addAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_ENTER));
		addAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(
				KeyEvent.VK_ENTER, ActionEvent.CTRL_MASK));
		
		
		Action viewAction = new AbstractAction("Povratak") {
			public void actionPerformed(ActionEvent event) {
				tmp.setVisible(false);
				owner.setEnabled(true);
			}
		};
		
		
		final JButton button;
		if (dialogtype == TYPE_ADD){
			button = new JButton(addAction);
			button.setText("Dodaj");
		}
		else if (dialogtype == TYPE_EDIT){
			button = new JButton(editAction);
			button.setText("Spremi");
		}
		else{
			button = new JButton(viewAction);
			// button = newJButton(view_Action);
			button.setText("Povratak");
		}
		gridPanel.add(new JLabel(""));
		gridPanel.add(button);

	}

	private Osoba napraviNovuOsobu(int tip, Osoba staraOsoba)
	{
		Osoba novaOsoba;
		if (tip == 0){
			novaOsoba = new Cuvar(staraOsoba.getIme(), staraOsoba.getPrezime(), staraOsoba.getJmbg(), staraOsoba.getPrebivaliste());
		}
		else if (tip == 1){
			novaOsoba = new Doktor(staraOsoba.getIme(), staraOsoba.getPrezime(), staraOsoba.getJmbg(), staraOsoba.getPrebivaliste(), "Opće prakse");
		}
		else{
			novaOsoba = new Zatvorenik(staraOsoba.getIme(), staraOsoba.getPrezime(), staraOsoba.getJmbg(), staraOsoba.getPrebivaliste(), "");
		}
		
		if (staraOsoba.getRodjen() != null)
			novaOsoba.setRodjen(staraOsoba.getRodjen());
		if (staraOsoba.getMedKarton() != null)
			novaOsoba.setMedKarton(staraOsoba.getMedKarton());
		if (staraOsoba.getDosje() != null)
			novaOsoba.setDosje(staraOsoba.getDosje());
		
		return novaOsoba;
		
	}
	
	protected boolean provjeriZanimanje(Osoba osoba, JComboBox tip) {
		
		return ( (osoba instanceof Cuvar && tip.getSelectedIndex() == 0) 
				|| (osoba instanceof Doktor && tip.getSelectedIndex() == 1)
				|| (osoba instanceof Zatvorenik && tip.getSelectedIndex()==2)); 
	}

	public Adresa getAddressToSave() {
		return addressToSave;
	}

	public void setAddressToSave(Adresa addressToSave) {
		this.addressToSave = addressToSave;
		
	}

	public JButton getAddressButton() {
		return addressButton;
	}

	public void setAddressButton(JButton addressButton) {
		this.addressButton = addressButton;
	}
	
	class AddressDialog extends JDialog {
		private static final long serialVersionUID = 517405257853010513L;
		
		private final JTextField ulica;
		private final JTextField kucniBroj;
		private final JTextField nazivMjesta;
		private final JTextField pbrMjesta;

		

		@SuppressWarnings("serial")
		public AddressDialog(final CoolDialog owner) {
			super(owner);
			owner.setEnabled(false);

			addWindowListener(new WindowAdapter() {
				@Override
				public void windowClosing(WindowEvent e) {
					owner.setEnabled(true);
				}
			});				
			
			Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
			setLocation(screenSize.width / 2 - 150, screenSize.height / 2 - 150);
			setSize(300, 300);

			setLayout(new BorderLayout());

			JPanel mainPanel = new JPanel();
			mainPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
			add(new JScrollPane(mainPanel));

			ulica = new JTextField();
			kucniBroj = new JTextField();
			nazivMjesta = new JTextField();
			pbrMjesta = new JTextField();
			
			if (dialogtype == TYPE_EDIT || dialogtype == TYPE_VIEW)
			{
				// Postavi
				Adresa adresaUredenika = uredenik.getPrebivaliste();
				if (adresaUredenika != null)
				{
					ulica.setText(adresaUredenika.getUlica());
					kucniBroj.setText(adresaUredenika.getKucniBroj());
					nazivMjesta.setText(adresaUredenika.getMjesto().getNaziv());
					pbrMjesta.setText(adresaUredenika.getMjesto().getPostBroj().toString());
				}
			}
			
			if (dialogtype == TYPE_VIEW)
			{
				ulica.setEditable(false);
				kucniBroj.setEditable(false);
				nazivMjesta.setEditable(false);
				pbrMjesta.setEditable(false);
			}

			JPanel gridPanel = new JPanel(new GridLayout(5, 2, 8, 8));
			mainPanel.add(gridPanel, BorderLayout.CENTER);

			gridPanel.add(new JLabel("Ulica: "));
			ulica.setPreferredSize(new Dimension(100, 20));
			gridPanel.add(ulica);

			gridPanel.add(new JLabel("Kućni broj: "));
			gridPanel.add(kucniBroj);

			gridPanel.add(new JLabel("Naziv mjesta: "));
			gridPanel.add(nazivMjesta);

			gridPanel.add(new JLabel("PBR Mjesta: "));
			gridPanel.add(pbrMjesta);

			final JDialog tmp = this;

			Action addAction = new AbstractAction("Dodaj") {
				public void actionPerformed(ActionEvent event) {
					if (ulica.getText().equals(""))
						JOptionPane.showMessageDialog(tmp,
								"Ulica nije dobro unešena!",
								"Pogreška kod unosa",
								JOptionPane.ERROR_MESSAGE);
					else if (kucniBroj.getText().equals(""))
						JOptionPane.showMessageDialog(tmp,
								"Kućni broj nije dobro unešen!",
								"Pogreška kod unosa",
								JOptionPane.ERROR_MESSAGE);
					else if (nazivMjesta.getText().equals(""))
						JOptionPane.showMessageDialog(tmp,
								"Mjesto nije dobro unešeno!",
								"Pogreška kod unosa",
								JOptionPane.ERROR_MESSAGE);

					else if (pbrMjesta.getText().equals(""))
						JOptionPane.showMessageDialog(tmp,
								"Poštanski broj nije dobro unešen!",
								"Pogreška kod unosa",
								JOptionPane.ERROR_MESSAGE);
					else
						try {
							owner.setAddressToSave(new Adresa(new Mjesto(
									nazivMjesta.getText(), Integer
											.valueOf(pbrMjesta.getText())),
									ulica.getText(), kucniBroj.getText()));
							owner.getAddressButton().setText(
									nazivMjesta.getText());
							tmp.setVisible(false);
							owner.setEnabled(true);
						} catch (NumberFormatException e) {
							JOptionPane.showMessageDialog(tmp,
									"Poštanski broj nije dobro unešen!",
									"Pogreška kod unosa!",
									JOptionPane.ERROR_MESSAGE);
						}
				}
			};
			addAction.putValue(Action.SHORT_DESCRIPTION, "Dodaj adresu.");
			addAction.putValue(Action.MNEMONIC_KEY, new Integer(
					KeyEvent.VK_ENTER));
			addAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(
					KeyEvent.VK_ENTER, ActionEvent.CTRL_MASK));
			
			Action viewAction = new AbstractAction("Povratak") {
				public void actionPerformed(ActionEvent event) {
					tmp.setVisible(false);
					owner.setEnabled(true);
				}};
			
			
			final JButton button;
			if (dialogtype != TYPE_VIEW)
			{
				button= new JButton(addAction);
				button.setText("Dodaj");
			}
			else{
				button = new JButton(viewAction);
				button.setText("Povratak");
			
			}
			gridPanel.add(new JLabel(""));
			gridPanel.add(button);

		}
		
		public JTextField getUlica() {
			return ulica;
		}

		public JTextField getKucniBroj() {
			return kucniBroj;
		}

		public JTextField getNazivMjesta() {
			return nazivMjesta;
		}

		public JTextField getPbrMjesta() {
			return pbrMjesta;
		}
		
	}

}
